const { Controller } = require('ee-core');
const Services = require('ee-core/services');
const Log = require('ee-core/log');
const Addon = require('ee-core/addon');
const md5 = require('crypto-js/md5');
const fs = require('fs');
const Ps = require('ee-core/ps');
const _ = require('lodash');

/**
 * 示例控制器
 * @class
 */
class CollectController extends Controller {

  constructor(ctx) {
    super(ctx);
  }

  /**
   * 所有方法接收两个参数
   * @param args 前端传的参数
   * @param event - ipc通信时才有值。详情见：控制器文档
   */
  async show(args, event){
    // const data = await Addon.get('collect').postArtsCollect();
    // return data
    const result = await Services.get('auction').show(args.id);
    var zcList = await Services.get('zc').list({auction_id: result.id}, 1000)
    if(zcList.length == 0 || args.requestData == 1) {
      //采集列表
      const data = await Addon.get('collect').auctionZc(result);
      //更新拍卖信息
      await Services.get('auction').update(result.id, {title: data.title, paddress: data.paddress,address: data.address, date: (data.date), pdate: (data.pdate)})
      //更新专场信息进数据库
      for(var i in data.zcList) {
        var arr = data.zcList[i]
        arr.id = md5(arr.url).toString()
        arr.auction_id = result.id
        arr.status = 0
        arr.countArts = 0
        // console.log(arr)
        await Services.get('zc').add(arr);
      }
      zcList = await Services.get('zc').list({auction_id: result.id}, 1000)
    }
    
    // await Addon.get('collect').postArtsCollect();
    // await Addon.get('collect').collectZc(result, result['zcList'][0], 1);

    return {code: 200, message: 'ok', data: {info:result, zcList}};
  }
  
  /**
   * test
   */
  async list (args, event) {
    // 前端参数
    const params = args;
    // 调用service
    var result = await Services.get('auction').list(50)
    if(params.token)await Services.get('auction').setToken(params.token)
    if(params.url) {
      result = [await Services.get('auction').find({url: params.url})];
    }

    for(var i in result) {
      result[i]['zc_num'] = await Services.get('zc').count({auction_id: result[i]['id']});
      result[i]['art_num'] = await Services.get('art').count({auction_id: result[i]['id']});
    }

    // await Addon.get('collect').postArtsCollect()

    return {code: 200, message: 'ok', data: {list: result}}
  }

  /**
   * 
   */
  async add (args, event) {
    // console.log(new Date().toLocaleDateString() + ' ' + new Date().toLocaleTimeString())
    // 前端参数
    const params = args
    // 调用service
    const result = await Services.get('auction').add(params);
    if(!result) {
      return {code: 400, message: '已存在', data: {}};
    }
    return {code: 200, message: 'ok', data: {code: 1}};
  }

  async delete (args, event) {

    // 前端参数
    const params = args;
    // 调用service
    const result = await Services.get('auction').delete(params.id)
    //删除专场
    await Services.get('zc').delete({auction_id: params.id})
    //删除艺术品
    await Services.get('art').delete({auction_id: params.id})

    return {code: 200, message: 'ok', data: {list: result}}
  }



  async updateZcStatus (args, event) {
    // 前端参数
    const params = args
    for(var i in params.ids){
        await Services.get('zc').update({
            id: params.ids[i].id,
            status: params.ids[i].status == 1?0:1
        });
    }
    return {code: 200, message: 'ok', data: {code: 1}};
  }

  async deleteZc (args, event) {
    // 前端参数
    const params = args
    const result = await Services.get('zc').delete(params.id);
    return {code: 200, message: 'ok', data: {code: result}};
  }

  async listZc (args, event) {
    // 前端参数
    const params = args
    const data = await Services.get('zc').list((val)=>{return val.status>0}, 100)
    return {code: 200, message: 'ok', data: {list: data}};
  }
  async listArt (args, event) {
    // 前端参数
    const params = args
    const data = await Services.get('art').list((val)=>{return val.status>=0}, 100)
    return {code: 200, message: 'ok', data: {list: data}};
  }
  async updateCollectConfig (args, event) {
    // 前端参数
    const params = args
    const data = await Addon.get('collect').getCollectConfig()
    return {code: 200, message: 'ok', data: {list: data}};
  }


  async log(args, event){
    const now = new Date();
    const year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    month = (month<10)?('0'+month.toString()):month
    day = (day<10)?('0'+day.toString()):day
    const logFilePath = Ps.getLogDir() + '/ee-' + `${year}${month}${day}.log`
    const logFilePathError = Ps.getLogDir() + '/ee-error-' + `${year}${month}${day}.log`
    var success = '-'
    var error = '-'
    if(await fs.existsSync(logFilePath)) success = await fs.readFileSync(logFilePath).toString()
    if(await fs.existsSync(logFilePathError)) error = await fs.readFileSync(logFilePathError).toString()
    const lines = Array.from(success.split('\n'))
    lines.reverse()
    const lines1 = Array.from(error.split('\n'))
    lines1.reverse()
    return {code: 200, message: 'ok', data: {success: lines.join('\n'), error: lines1.join('\n')}}
  }

  async getRule(){
    const data = await Addon.get('collect').collectField
    return {code: 200, message: 'ok', data: {list: data}}
  }
  async testRule(args, event){
    await Addon.get('collect').setRuleContent(args.form)
    const auction = {url: args.form.url, collect_id: args.form.collect_id, id:0}
    const data = await Addon.get('collect').auctionZc(auction);
    if(data.zcList.length >0) {
      data.zcList = _.head(data.zcList)
      data.arts = await Addon.get('collect').collectZc(auction, data.zcList, 1)
    }
    return {code: 200, message: 'ok', data: {list: data}}
  }
}  


CollectController.toString = () => '[class ExampleController]';
module.exports = CollectController;  